/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Platform,
  ListView,
  Image,
  Dimensions,
  ActivityIndicator,
  RefreshControl,
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';
import Mock from 'mockjs';
import Request from '../Common/Request';
import Config from '../Common/Config';
import Item from './Item';
import Detail from './Detail';

const {width, height} = Dimensions.get('window');

export default class List extends Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            loadingTail: false,
            page: 0,
            items: [],
            total: 0,
            isRefreshing: false,
        };
    }

    componentDidMount() {
        this._fetchData(1)
    }

    _fetchData(page) {
        Request.get(Config.api.base + Config.api.list, {
            accessToken: 'kelvin',
            page: page
        })
        .then((responseData) => {
            if (responseData.success) {
                let oldItems = this.state.items.slice()
                let newItems = []
                if (oldItems.length === 0) {
                    newItems = responseData.data
                } else {
                    if (page === 0) {
                        newItems = responseData.data.concat(oldItems)
                    } else {
                        newItems = oldItems.concat(responseData.data)
                    }
                }

                console.log('total: ' + responseData.total);
                console.log('current: ' + responseData.data.length);

                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(newItems),
                    loadingTail: false,
                    isRefreshing: false,
                    total: responseData.total,
                    items: newItems,
                })
            }
        })
        .catch((error) => {
            console.log(error);
            this.setState({
                loadingTail: false,
            })
        })
    }

    // 上拉加载
    _fetchMoreData() {
        if (!this._hasMore() || this.state.loadingTail) {
            return
        }

        this.setState({
            page: this.state.page + 1,
            loadingTail: true,
        })
        this._fetchData(this.state.page)
    }

    // 下拉刷新
    _onRefresh() {
        if (!this._hasMore() || this.state.isRefreshing) {
            return
        }

        this.setState({
            isRefreshing: true,
        })
        this._fetchData(0)
    }

    _hasMore() {
        if (this.state.total === 0) {
            return true
        }

        return this.state.items.length !== this.state.total
    }

    _renderRow(data) {
        return (
            <Item
                rowData={data}
                key={data._id}
                onSelect={(rowData) => this._loadDetailPage(rowData)}
            />
        )
    }

    _renderFooter() {
        if (!this._hasMore()) {
            return (
                <View style={styles.footerView}>
                    <Text style={styles.footerText}>
                        没有更多数据了...
                    </Text>
                </View>
            )
        }
        if (!this.state.loadingTail) {
            return (
                <View style={styles.footerView}>
                    <Text style={styles.footerText}>
                        上拉加载更多...
                    </Text>
                </View>
            )
        }
        return (
            <View style={styles.footerView}>
                <Text style={styles.footerText}>
                    努力加载中...
                </Text>
                <ActivityIndicator
                />
            </View>
        )
    }

    _loadDetailPage(data) {
        let {navigator} = this.props;
        if (navigator) {
            navigator.push({
                name: 'Detail',
                component: Detail,
                params: {
                    data: data
                }
            })
        }
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <Text style={styles.headerText}>
                        视频列表
                    </Text>
                </View>

                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={this._renderRow.bind(this)}
                    enableEmptySections={true}
                    automaticallyAdjustContentInsets={false}
                    style={styles.listview}
                    onEndReached={this._fetchMoreData.bind(this)}
                    onEndReachedThreshold={20}
                    renderFooter={this._renderFooter.bind(this)}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh.bind(this)}
                        />
                    }
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  header: {
      marginTop: Platform.OS === 'ios' ? 20 : 0,
      paddingTop: 25,
      paddingBottom: 12,
      backgroundColor: '#ee735c'
  },
  headerText: {
      fontSize: 16,
      fontWeight: '600',
      textAlign: 'center',
      color: '#fff',
  },
  listview: {
      backgroundColor: '#f5fcff',
  },
  footerView: {
      marginVertical: 20,
      flexDirection: 'row',
      justifyContent: 'center',
  },
  footerText: {
      textAlign: 'center',
      fontSize: 18,
      color: 'red',
      marginRight: 10,
  },
});
